<template>
	<view class="photo">
		<before-select
		  class="befor-select"
		  v-show="uploadBefore"
			@uploadImg="uploadImg"
			:imageList="imageList"
			@selectType="selectType"
			:image="image"
			:active="active"
			:target="target"
			ref="bef"
		></before-select>
			<selected-img
			  ref="sonProgress"
			  class="select-img"
			  v-show="!uploadBefore"
			  :imgUrl="imgPath"
				@startMake="startMake"
				:progress="progress"
				:percent="percent"
				:percents="percents"
				@reSelect="uploadImg"
				:success="success"
				@saveImg="saveImg"
				@shareFriend="shareFriend"
				@lookImg="lookImg"
				:title="title"
		  ></selected-img>
			
			<view class="look-box" v-if="imgUrlPath">
				<movable-area scale-area>
					<movable-view direction="all" @scale="onScale" scale="true" scale-min="1" scale-max="4">
						<image mode="widthFix" :src="imgUrlPath" @click="imgUrlPath=''"></image>
					</movable-view>
				</movable-area>
			</view>
			
	</view>
</template>
<script>
import { getToolList, getUploadUrl, getFileUrl, taskExec } from '@/api/task.js'
import { Base64 } from '@/static/base64.js'
import compareImage from '@/components/compare.vue'
import beforeSelect from '@/components/beforSelect.vue'
import selectedImg from '@/components/selectedImg.vue'
import progressCircle from '@/components/progress.vue'

export default {
	components: { compareImage, beforeSelect, selectedImg, progressCircle },
	data() {
		return {
			image: {
				beforeImg: '',
				afterImg: '',
			}, // 示例动图照片
			imageList: [], // 处理照片的类型列表
			imgPath: '', // 选择图片后的图片地址
			uploadBefore: true,
			title: '', // 点击工具传过来的标题
			productCode: '', // 处理照片类型
			taskid: '', // 任务id，从后端获取
			progress: true, // 进度条显示
			percent: 0.1, // 进度条
			percents: 10,
			setTime: null, // 定时器
			active: 0,
			success: false,
			target: true,
			text: '任务执行中，请勿离开页面',
			time2: null,
			flag: false,
			imgUrlPath: ''
		}
	},
	onLoad(param) {
		this.title = param.title;
		uni.setNavigationBarTitle({
		  title: param.title
		})
	},
	onShow() {
		this.getTools();
	},
	onUnload() {
		clearTimeout(this.time2)
		clearInterval(this.timeSet)
	},
	
	onShareTimeline() {
		return {
			title: this.title,
			// query: 'item=' + this.info
		}
	},
	onShareAppMessage() {
		return {
			title: this.title,
			path: '/pages/photo/index'
		}
	},
	watch:{
		// percent(val) {
		// 	console.log('val', val)
		// 	this.percents = val * 100
		// }
	},
	methods: {
		// 查看图片
		lookImg() {
			this.imgUrlPath = this.imgPath;
		},
		async getTools() {
			this.imageList = [];
			const tool = await getToolList();
			console.log('tool', tool)
			const { image } = tool.data;
			// 拿到图像工具列表，根据标题显示不同的样例
			image.forEach(ele => {
				// 原来的工具
				// if(this.title == '照片修复') {
				// 	this.image = {
				// 		beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairBefore.png',
				// 		afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairAfter.png'
				// 	}
				// 	if(ele.product_code == 'image-ddcolor-colorization'  || ele.product_code == 'image-portrait-enhancement') {
				// 		this.imageList.push(ele);
				// 	}
				// } else if (this.title == '人像风格') {
				// 	this.image = {
				// 		beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonBefore.png',
				// 		afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonAfter.png'
				// 	}
				// 	if(ele.product_code == 'image-cartoon-sd-illustration' || ele.product_code == 'image-cartoon-handdrawn' || ele.product_code == 'image-cartoon-3d-compound') {
				// 		if(ele.title == '人像卡通化-手绘风') {
				// 			ele.title = '卡通手绘风'
				// 		} else if(ele.title == '人像卡通化-漫画风') {
				// 			ele.title = '卡通漫画风'
				// 		} else if(ele.title == '人像生成卡通化3D') {
				// 			ele.title = '卡通3D风'
				// 		}
				// 		this.imageList.push(ele);
				// 	}
				// } else if (this.title == '智能抠图') {
				// 	this.image = {
				// 		beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentBefore.jpg',
				// 		afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentAfter.png'
				// 	}
				// 	if(ele.product_code == 'image-remove-universal-matting' || ele.product_code == 'image-remove-background') {
				// 		this.imageList.push(ele);
				// 	}
				// }
				
				
				if(this.title == '照片修复') {
					this.image = {
						beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairBefore.png',
						afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairAfter.png'
					}
					if(ele.product_code == 'image-ddcolor-colorization') {
						this.imageList.push(ele);
					}
				} else if (this.title == '清晰度增强') {
					this.image = {
						beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/vagueBefore.png',
						afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/vagueAfter.png'
					}
					if(ele.product_code == 'image-portrait-enhancement') {
						this.imageList.push(ele);
					}
				} else if (this.title == '人像风格') {
					this.image = {
						beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonBefore.png',
						afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonAfter.png'
					}
					if(ele.product_code == 'image-cartoon-sd-illustration' || ele.product_code == 'image-cartoon-handdrawn' || ele.product_code == 'image-cartoon-3d-compound') {
						if(ele.title == '人像卡通化-手绘风') {
							ele.title = '卡通手绘风'
						} else if(ele.title == '人像卡通化-漫画风') {
							ele.title = '卡通漫画风'
						} else if(ele.title == '人像生成卡通化3D') {
							ele.title = '卡通3D风'
						}
						this.imageList.push(ele);
					}
				} else if (this.title == '通用抠图') {
					this.image = {
						beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentBefore.jpg',
						afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentAfter.png'
					}
					if(ele.product_code == 'image-remove-universal-matting') {
						this.imageList.push(ele);
					}
				} else if (this.title == '人像抠图') {
					this.image = {
						beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cutoutBefore.jpg',
						afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cutoutAfter.png',
					}
					if(ele.product_code == 'image-remove-background') {
						this.imageList.push(ele);
					}
				}
			});
			
			
			
			// 给照片处理的类型添加图片
			this.imageList.forEach(item => {
				if(item.product_code == 'image-ddcolor-colorization') {
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairBefore.png'
				} else if (item.product_code == 'image-portrait-enhancement') {
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/vagueBefore.png'
				} else if (item.product_code == 'image-cartoon-sd-illustration') {
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonBefore.png'
				} else if (item.product_code == 'image-cartoon-handdrawn') {
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/drawnBefore.jpg'
				} else if (item.product_code == 'image-cartoon-3d-compound') {
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/3DBefore.png'
				} else if (item.product_code == 'image-remove-universal-matting') {
					// item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cutoutBefore.jpg'
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentBefore.jpg'
				} else if (item.product_code == 'image-remove-background') {
					// item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentBefore.jpg'
					item.imgUrl = 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cutoutBefore.jpg'
				}
			});
			// code默认为第一个
			this.productCode = this.imageList[0].product_code;
		},
		uploadImg() {
			if(!uni.getStorageSync('apiticket')){
				uni.showModal({
					title: "提示",
					content: "请先登录",
					success(res) {
						if(res.confirm){
							setTimeout(() => {
								uni.navigateTo({
									url: "/pages/login/index",
								})
							}, 1000);
						}
					},
				});
				return
			}
			uni.chooseImage({
				success: (res) => {
					console.log('成功res', res)
					const tempFilePaths = res.tempFilePaths;
					const filePath = tempFilePaths[0]; // 选择第一张图片
					const fileName = tempFilePaths[0].match(/(.*\/)*(.*)$/)[2];
					
					const fileSystemManager = wx.getFileSystemManager();
					 
					// 读取文件
					fileSystemManager.readFile({
						filePath: filePath,
						success: (readRes) => {
							// 在这里处理文件流，readRes.data就是文件的二进制数据
							console.log('文件流：', readRes.data);
							this.uploadFile(fileName, this.productCode, readRes.data);
						},
						fail: (err) => {
							console.error('读取文件失败：', err);
						}
					});
				
				},
			})
		},
		
		// 获取地址上传文件
		async uploadFile(name, code, pathData) {
			uni.showLoading({
				title: '正在上传图片...'
			})
			let data = {
				filename: name,
				product_code: code
			}
			// 获取文件上传的地址
			const uploadRes = await getUploadUrl(data);
			const { url, token, taskid } = uploadRes;
			this.taskid = taskid;
			
			// monio直传
			uni.request({
				url: url,//后端返回的签名地址
				data: pathData , //上传的文件字节流
				method: 'PUT',
				header: {
					'Content-Type': 'application/octet-stream', //此处注意
					'Content-Disposition':'inline'
				},
				success: (minio) => {
					console.log("直传返回", minio);
					// 上传到minio成功后储存到服务器
					let tokenStr = { token: token }
					getFileUrl(tokenStr).then(urlRes => {
						console.log('urlRes', urlRes);
						const { domain, filename } = urlRes.data;
						this.imgPath = domain + filename; // 显示图片
						this.uploadBefore = false; // 上传成功后显示图片组件
						uni.hideLoading()
					})
				}
			});
		},
		
		// 开始制作
		startMake() {
			this.progress = false;
			console.log('this.progress', this.progress)
			let param = {
				taskid: this.taskid
			}
			taskExec(param).then(res => {
				console.log('res', res);
				const { domain, taskid, domain_socket } = res;
				const webUrl = `wss://${domain_socket}/api/v1?clienid=${taskid}`
				console.log('webUrl', webUrl)
				this.testAI(webUrl)
			}).catch(err =>{
				this.progress = true;
			})
		},
		
		// 接入see
		testAI(seeUrl) {
			
			const webs = uni.connectSocket({
				url: seeUrl,
				header: {
					'content-type': 'application/json'
				},
				success: (res) => {
					console.log(res)
				},
				fail: (err) => {
					console.log(err)
				}
			})
			webs.onOpen((e) => {
				console.log('open', e)
				// 进度条
				this.setTime = setInterval(() => {
					this.percent += 0.03;
					this.percents += 3;
					this.$refs.sonProgress.$refs.progress.drawCircle(this.percent)
					if(this.percent > 0.9) {
						this.percents = 96
						this.percent = 0.96
						console.log('hfhfhfhfhf90')
						clearInterval(this.setTime);
					}
				}, 1000);
				
			})
			webs.onError((e) => {
				console.log('err', e)
				this.progress = false;
				this.uploadBefore = false;
				uni.showToast({
					title: e.errMsg,
					icon:'none'
				})
			})
			webs.onMessage((e) => {
				console.log('message', JSON.parse(e.data));
				const successData = JSON.parse(e.data);
				const successCode = successData.msg_content;
				if (successCode.data && successCode.errcode == '200') {
					this.flag = true
					this.imgPath = successCode.data;
					this.percent = 10;
					this.percents = 100;
					this.progress = true;
					this.success = true;
					clearTimeout(this.time2)
				}
			})
			webs.onClose((e)=>{
				console.log('close', e)
				if(!this.flag) {
					uni.showToast({
						title: '连接断开，请稍后再试',
						icon: 'none',
						duration:3000
					})
					clearInterval(this.setTime);
					this.percent = 0;
					this.percents = 0;
					this.progress = true;
					// this.success = false;
					this.uploadBefore = true;
					clearTimeout(this.time2)
				}
			})
			
			// 300秒关闭连接
			this.time2 = setTimeout(function() {
				uni.showToast({
					title: '超时，请重试',
					icon: 'none'
				})
			  uni.closeSocket(webs);
			}, 300000); // 300000
		},
		
		// 选择处理照片的形式
		selectType(item, index) {
			this.target  = false;
			// this.$refs.bef.changeFun()
			console.log('item', item);
			this.productCode = item.product_code;
			this.active = index
			if(item.product_code == 'image-portrait-enhancement') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/vagueBefore.png',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/vagueAfter.png'
				}
			} else if(item.product_code == 'image-ddcolor-colorization') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairBefore.png',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/repairAfter.png'
				}
			} else if(item.product_code == 'image-cartoon-sd-illustration') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonBefore.png',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cartoonAfter.png'
				}
			} else if(item.product_code == 'image-cartoon-handdrawn') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/drawnBefore.jpg',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/drawnAfter.png'
				}
			} else if(item.product_code == 'image-cartoon-3d-compound') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/3DBefore.png',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/3DAfter.png'
				}
			} else if(item.product_code == 'image-remove-universal-matting') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cutoutBefore.jpg',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/cutoutAfter.png',
				}
			} else if(item.product_code == 'image-remove-background') {
				this.image = {
					beforeImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentBefore.jpg',
					afterImg: 'https://oss.aimlt.com/webui-static/aiyunyi-app/image/currentAfter.png'
				}
			}
			setTimeout(() => {
				this.target  = true
			}, 500)
		},
		// 保存图片
		saveImg() {
			uni.showLoading({
				title: '请稍等...'
			})
			wx.downloadFile({
				url: this.imgPath, //分享的图片的链接
				success: (res) => {
					uni.hideLoading()
					console.log('res', res)
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function() {
							uni.hideLoading()
							uni.showModal({
								title: '保存成功',
								content: '图片已成功保存到相册',
								showCancel: false
							});
						},
						complete(res) {
							uni.hideLoading()
							console.log(res);
						}
					});
				}
			})
			// this.preservationImg(this.imgPath)
		},
		// 分享好友
		shareFriend() {
			uni.showLoading({
				title: '请稍等...'
			})
			wx.downloadFile({
				url: this.imgPath, //分享的图片的链接
				success: (res) => {
					console.log('res', res)
					uni.hideLoading()
					wx.showShareImageMenu({
						path: res.tempFilePath,
						success: (re) => {
							console.log('分享成', re)
						},
						fail: (re) => {
							console.log({ fail: re })
						}
					})
				}
			})
		},
		
		
		preservationImg(img) {
			uni.showLoading({
				title: '请稍等...'
			})
			let that = this
			uni.authorize({
		        /* scope.writePhotosAlbum 类型是保存到相册 */
				scope: 'scope.writePhotosAlbum',
				success() {
		            /* 已授权进入 */
					/* 保存图片到相册方法方法 */
					that.imgApi(img);
					uni.hideLoading()
				},
				complete(res) {
					/* 判断如果没有授权就打开设置选项让用户重新授权 */
				    uni.getSetting({
							success(res) {
								if (!res.authSetting['scope.writePhotosAlbum']) {
								 /* 打开设置的方法 */
									that.opensit();
									uni.hideLoading()
								}
							}
				    });
			    }
			});
		},
		imgApi(image) {
				/* 获取图片的信息 */
				uni.getImageInfo({
					src: image,
					success: function(image) {
						uni.hideLoading()
						/* 保存图片到手机相册 */
						uni.saveImageToPhotosAlbum({
							filePath: image.path,
							success: (re) => {
								uni.showModal({
									title: '保存成功',
									content: '图片已成功保存到相册',
									showCancel: false
								});
								
								
								
							},
						complete(res) {
							console.log(res);
						}
					});
				}
			});
		},
		
		opensit() {
			uni.showModal({
				content: '没有授权保存图片到相册,点击确定去允许授权',
				success: function(res) {
					if (res.confirm) {
						/* 打开设置的API*/
						uni.openSetting({
							success(res) {
								console.log(res.authSetting);
							}
						});
					} else if (res.cancel) {
						uni.showModal({
							cancelText: '取消',
							confirmText: '重新授权',
							content: '你点击了取消，将无法进行保存操作',
							success: function(res) {
								if (res.confirm) {
									uni.openSetting({
										success(res) {
											/* 授权成功 */
											console.log(res.authSetting);
										}
									});
								} else if (res.cancel) {
									console.log('用户不授权');
								}
							}
						});
					}
				}
			});
		},
					
	},
}
</script>
<style lang="scss" scoped>
	.photo {
		margin: 40rpx;
		position: relative;
		.select-img {
			position: absolute;
			left: 50%;
			transform: translate(-50%);
		}
	}
	
	.image{
		// margin: 40rpx 60rpx;
	}
	.img {
		
		width: 600rpx;
		height: 600rpx;
		border-radius: 20rpx;
		
		.img-size {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}
	}
	.img-btn{ 
		display: flex;
		.btn {
			background: #ff6005;
			border-radius: 60rpx;
			width: 280rpx;
			color: #fff;
		}
		.reselect {
			background: transparent;
			color: #ff6005;
			border: 1px solid #ff6005;
			margin-left: 20rpx;
		}
	}
	// .progress {
	// 	position: fixed;
	// 	bottom: 20rpx;
	// }
	// .progress-text {
	// 	text-align: center;
	// 	margin-top: 400rpx;
	// }
	
	
	movable-view {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
	}
	
	movable-area {
		height: 100%;
		width: 100%;
		position: fixed;
		overflow: hidden;
	}
	
	movable-view image {
		width: 100%;
	}
	
	.look-box {
		height: 100%;
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.8);
		display: flex;
		align-items: center;
	
		.look-btn {
			width: 100%;
			position: fixed;
			bottom: var(--window-bottom);
			left: 0;
			z-index: 2;
			background-color: rgba(0, 0, 0, 0.1);
			padding: 20rpx 20rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;
	
			.other {
				font-size: 26rpx;
				color: #efefef;
				width: 500rpx;
	
				.name {
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
	
			.btn {
				width: 140rpx;
				display: flex;
				justify-content: space-between;
			}
		}
	
		.icon {
			position: absolute;
			top: calc(var(--window-top) + 20rpx);
			right: 10rpx;
		}
	
		image {
			width: 100%;
		}
	}
	
</style>